//封装axios
import axios from "axios"

//随便写个XJB变量名创建axios实例
let instance = axios.create({
    //设置基础路径
    baseURL: "http://localhost:3000",
    //设置超时
    timeout: 5000,
})

//配置axios请求拦截器，拦截添加token再发送
instance.interceptors.request.use((config) => {
    //获取token
    let token = localStorage.token
    //添加token到header的Authorization属性
    config.headers.Authorization = "Bearer " + token
    return config
}, (err) => {
    //拦截错误
    return err
})

//配置axios响应拦截器
instance.interceptors.response.use((res) => {
    //响应成功执行
    return res
}, (err) => {
    //响应错误执行
    if (err && err.response) {
        //判断错误类型，添加描述
        switch (err.response.status) {
            case 400: err.message = '请求错误(400)'; break;
            case 401: err.message = '身份认证失败(401)'; break;
            case 403: err.message = '拒绝访问(403)'; break;
            case 404: err.message = '请求出错(404)'; break;
            case 408: err.message = '请求超时(408)'; break;
            case 500: err.message = '服务器错误(500)'; break;
            case 501: err.message = '服务未实现(501)'; break;
            case 502: err.message = '网络错误(502)'; break;
            case 503: err.message = '服务不可用(503)'; break;
            case 504: err.message = '网络超时(504)'; break;
            case 505: err.message = 'HTTP版本不受支持(505)'; break;
            default: err.message = `连接出错(${err.response.status})!`;
        }
    } else {
        err.message = "Unable to establish connection with server"
    }
    //返回的所有响应结果，需要包装成统一格式
    return {
        data: {
            status: 0,
            message: err.message
        }
    }
})

//将实例暴露
export default instance